<script setup lang="tsx">
import Write from './components/Write.vue'
import Material from './components/Material.vue'
import { ContentDetailWrap } from '@/components/ContentDetailWrap'
import { Dialog } from '@/components/Dialog'
import { Table } from '@/components/Table'
import { computed, nextTick, onMounted, reactive, ref, unref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { useRoute, useRouter } from 'vue-router'
import { useEventBus } from '@/hooks/event/useEventBus'
import { Form, FormSchema } from '@/components/Form'
import {
  ElButton,
  ElCheckbox,
  ElCol,
  ElCollapse,
  ElCollapseItem,
  ElDatePicker,
  ElDivider,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElRow,
  ElTag
} from 'element-plus'
import { addFemaleApi, getFemaleApi, putFemaleApi, putFemaleVersionApi } from '@/api/check/female'
import { getParamOptionApi } from '@/api/check/param'
import { Icon } from '@/components/Icon'
import { TableColumn } from '@/components/Table'
import { FemaleType, FemaleWriteType } from '@/api/check/female/types'
import Standard from '@/views/Check/Sample/Standard/index.vue'
import { useIcon } from '@/hooks/web/useIcon'

const { emit } = useEventBus()

const { push, go } = useRouter()
const route = useRoute()

const { t } = useI18n()

const paramOptions = ref()

const getParamOption = async () => {
  const res = await getParamOptionApi()
  if (res) paramOptions.value = res.data
}

getParamOption()

const productTypeOptions = computed(() =>
  paramOptions.value ? paramOptions.value.filter((item) => item.param_type == '型号') : []
)
const partTypeOptions = computed(() =>
  paramOptions.value ? paramOptions.value.filter((item) => item.param_type == '材料') : []
)

const schema = reactive<FormSchema[]>([
  {
    field: 'part_no',
    label: '材料/零件图号',
    colProps: {
      span: 6
    },
    formItemProps: {
      slots: {
        default: (data) => {
          return (
            <ElInput
              v-model={data.part_no}
              placeholder="请输入"
              v-slots={{
                append: () => (
                  <ElButton
                    onClick={() => (dialogVisible.value = true)}
                    icon={useIcon({ icon: 'ep:circle-plus' })}
                  />
                )
              }}
            />
          )
        }
      }
    }
  },
  {
    field: 'part_name',
    label: '材料/零件名称',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'material_no',
    label: '物料编号',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'product_type',
    label: '型号',
    colProps: {
      span: 6
    },
    component: 'Select',
    componentProps: {
      options: productTypeOptions
    }
  },
  {
    field: 'part_type',
    label: '材料类型',
    colProps: {
      span: 6
    },
    component: 'Select',
    componentProps: {
      options: partTypeOptions
    }
  },
  {
    field: 'material_type',
    label: '物料类型',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'is_sampling',
    label: '抽检',
    colProps: {
      span: 6
    },
    component: 'Select',
    componentProps: {
      options: [
        {
          label: '是',
          value: true
        },
        {
          label: '否',
          value: false
        }
      ]
    }
  },
  {
    field: 'plan_remark',
    label: '计划备注',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'required_dimension',
    label: '要求尺寸',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: 'remark',
    label: '备注',
    colProps: {
      span: 6
    },
    component: 'Input'
  },
  {
    field: '',
    colProps: {
      span: 24
    },
    formItemProps: {
      slots: {
        default: (data) => {
          const tableColumns1 = reactive<TableColumn[]>([
            {
              field: 'selection',
              fixed: true,
              width: 120,
              slots: {
                default: (scope) => <ElCheckbox v-model={scope.row.check} />
              },
              align: 'left'
            },
            {
              field: 'project',
              label: '检验项目',
              minWidth: 120,
              slots: {
                default: (scope) => <ElInput v-model={scope.row!.project} />
              }
            },
            {
              field: 'detail',
              label: '检验明细',
              minWidth: 120,
              slots: {
                default: (scope) => <ElInput v-model={scope.row!.detail} />
              }
            },
            // {
            //   field: 'attachment',
            //   label: '检验图片',
            //   minWidth: 120,
            //   slots: {
            //     default: (scope) => <ElInput v-model={scope.row!.attachment} />
            //   }
            // },
            {
              field: 'action',
              label: '操作',
              minWidth: 80,
              slots: {
                default: (scope) =>
                  scope.row.children ? (
                    <ElButton
                      onClick={() => {
                        scope.row.children.push({
                          content_type: '检验项目',
                          project: '',
                          detail: [],
                          attachment: ''
                        })
                      }}
                    >
                      新增
                    </ElButton>
                  ) : (
                    <></>
                  )
              }
            }
          ])
          const tableColumns2 = reactive<TableColumn[]>([
            {
              field: 'selection',
              fixed: true,
              width: 80,
              slots: {
                default: (scope) => <ElCheckbox v-model={scope.row.check} />
              }
            },
            {
              field: 'index',
              label: t('common.index'),
              type: 'index',
              minWidth: 80,
              fixed: true
            },
            {
              field: 'part_no',
              label: '材料/零件图号',
              minWidth: 120
            },
            {
              field: 'characteristic',
              label: '特征',
              minWidth: 120
            },
            {
              field: 'dimension',
              label: '尺寸',
              minWidth: 120
            },
            {
              field: 'irr',
              label: '初始可靠值',
              minWidth: 120
            },
            {
              field: 'grade',
              label: '等级',
              minWidth: 120
            }
          ])
          const filterContentByType = (type) => {
            return data.contents?.filter((v) => v.content_type == type) || []
          }
          return (
            <ElCollapse accordion class="w-full">
              <ElCollapseItem title="零件/材料标记" name="Part_Material_Identification">
                <ElForm labelWidth="auto" labelPosition="right">
                  <ElRow gutter={20}>
                    <ElCol span={8}>
                      <ElFormItem label="图号/件号/材料牌号">
                        <ElInput v-model={data.draw_no} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="更改字母">
                        <ElInput v-model={data.rev_letter} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="状态">
                        <ElInput v-model={data.temper} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="规范/标准">
                        <ElInput
                          v-model={data.spec_stan}
                          v-slots={{
                            append: () => (
                              <ElButton
                                onClick={() => (standVisible.value = true)}
                                icon={useIcon({ icon: 'ep:circle-plus' })}
                              />
                            )
                          }}
                        />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="规范/标准版次">
                        <ElInput v-model={data.spec_stan_rev} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="工艺材料编号">
                        <ElInput v-model={data.zpm_cpm} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="型别">
                        <ElInput v-model={data.typing} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="类别/组合物别">
                        <ElInput v-model={data.classing} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="级别">
                        <ElInput v-model={data.grade} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="形态/形式">
                        <ElInput v-model={data.form} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="规格">
                        <ElInput v-model={data.size} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="色号">
                        <ElInput v-model={data.color} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="性能要求">
                        <ElInput v-model={data.special_property} />
                      </ElFormItem>
                    </ElCol>
                  </ElRow>
                </ElForm>
              </ElCollapseItem>
              <ElCollapseItem title="检验/验证特性" name="Inspected_Characteristic">
                <Table
                  data={filterContentByType('检验项目')}
                  columns={tableColumns1}
                  defaultExpandAll
                ></Table>
              </ElCollapseItem>
              <ElCollapseItem title="实验要求" name="Required_Test">
                <ElRow gutter={20}>
                  <ElCol span={6}>
                    <ElFormItem label="试样规格/尺寸">
                      <ElInput v-model={data.pclr_size} />
                    </ElFormItem>
                  </ElCol>
                  <ElCol span={6}>
                    <ElFormItem label="试样数量">
                      <ElInput v-model={data.pclr_quantity} />
                    </ElFormItem>
                  </ElCol>
                </ElRow>
                <ElDivider class="m-0" />
                <ElForm labelWidth="auto" labelPosition="right" class="ml-10">
                  {filterContentByType('实验要求').map((item) => {
                    return (
                      <div class="flex mb-10px">
                        <ElCheckbox label={item.project} v-model={item.check} />
                        {item.detail.map((detail, i) => {
                          return (
                            <div class="flex items-center	ml-10px">
                              <ElInput v-model={item.detail_value[i]} placeholder={detail} />
                            </div>
                          )
                        })}
                      </div>
                    )
                  })}
                </ElForm>
              </ElCollapseItem>
              <ElCollapseItem title="限制要求" name="Limit_Requirement">
                <ElForm labelWidth="auto" labelPosition="right" class="ml-10">
                  {filterContentByType('限制要求').map((item) => {
                    return (
                      <div class="flex mb-10px">
                        <ElCheckbox label={item.project} v-model={item.check} />
                        {item.detail.map((detail, i) => {
                          return (
                            <div class="flex items-center	ml-10px">
                              <ElInput v-model={item.detail_value[i]} placeholder={detail} />
                            </div>
                          )
                        })}
                      </div>
                    )
                  })}
                </ElForm>
              </ElCollapseItem>
              <ElCollapseItem title="ASR检验信息" name="ASR_Inspect">
                <Table data={data.asr_features} columns={tableColumns2} class="w-full" />
              </ElCollapseItem>
              <ElCollapseItem title="限寿要求" name="Life_Limit">
                <ElForm labelWidth="auto" labelPosition="right" class="ml-10">
                  <ElRow gutter={20}>
                    <ElCol span={2}>
                      <ElCheckbox v-model={data.is_life_limit} label="是否限寿件" />
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="工程要求">
                        <ElInput v-model={data.life_limit_req} />
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={8}>
                      <ElFormItem label="基准日期">
                        <div class="flex flex-nowrap">
                          <ElInput v-model={data.life_limit_manage} placeholder="管控方式" />
                          <ElDatePicker
                            v-model={data.life_limit_date}
                            valueFormat="YYYY-MM-DD HH:mm:ss"
                            class="ml-10px"
                          />
                        </div>
                      </ElFormItem>
                    </ElCol>
                    <ElCol span={6}>
                      <ElFormItem label="库房存储期限">
                        <ElInput v-model={data.life_limit_period} />
                      </ElFormItem>
                    </ElCol>
                  </ElRow>
                </ElForm>
              </ElCollapseItem>
            </ElCollapse>
          )
        }
      }
    }
  }
])

const currentRow = ref<FemaleWriteType>({
  asr_features: [] as any[],
  contents: [] as any[]
})

const materialRef = ref<ComponentRef<typeof Material>>()
const dialogVisible = ref(false)

const onSelectPart = async () => {
  const write = unref(materialRef)
  const formData = await write?.submit()
  if (formData) currentRow.value = { ...currentRow.value, ...formData }
  dialogVisible.value = false
}

const writeRef = ref<ComponentRef<typeof Write>>()

const loading = ref(false)

const save = async (data: Recordable | undefined) => {
  const formData = await unref(writeRef)?.submit()
  if (formData) {
    try {
      loading.value = true
      if (currentRow.value.id) {
        const res = await putFemaleApi({ ...formData, ...data })
        if (res) currentRow.value = res.data
      } else {
        const res = await addFemaleApi({ ...formData, ...data })
        if (res) push(`/check/female-add/${res.data.id}`)
      }
    } finally {
      loading.value = false
    }
  }
}

const upVersion = async () => {
  const formData = await unref(writeRef)?.submit()
  if (formData) {
    try {
      loading.value = true
      if (!currentRow.value.id) {
        ElMessage.warning('未保存的母本，不可升版')
        return
      }
      const res = await putFemaleVersionApi({ ...formData, id: currentRow.value.id })
      if (res) refresh()
    } finally {
      loading.value = false
    }
  }
}

// 选择标准
const standRef = ref<ComponentRef<typeof Standard>>()
const standVisible = ref(false)

const onSelectStand = async () => {
  const write = unref(standRef)
  const formData = await write?.submit()
  if (formData) {
    currentRow.value = {
      ...currentRow.value,
      spec_stan: formData[0].standard,
      spec_stan_rev: 'V1'
    }
  }
  standVisible.value = false
}

// 刷新表单
const refresh = async (data: any | undefined = undefined) => {
  const id = data?.id || currentRow.value?.id
  if (id) {
    const res = await getFemaleApi({ id })
    if (res) currentRow.value = res.data
  }
}

onMounted(async () => {
  const params = {
    ...route.params,
    ...route.query
  }
  refresh(params)
})
</script>

<template>
  <ContentDetailWrap>
    <Write ref="writeRef" :form-schema="schema" :current-row="currentRow" />
    <template #header>
      <div class="flex justify-between items-center">
        <div>
          <ElButton @click="push('/check/female')">
            {{ t('common.back') }}
          </ElButton>
          <ElButton
            type="primary"
            :loading="loading"
            @click="save"
            v-if="currentRow.status != '启用'"
          >
            {{ t('common.save') }}
          </ElButton>
          <ElButton
            type="primary"
            :loading="loading"
            @click="() => save({ status: '启用' })"
            v-if="currentRow.status != '启用'"
          >
            {{ '启用' }}
          </ElButton>
          <ElButton
            type="primary"
            :loading="loading"
            @click="upVersion"
            v-if="currentRow.status == '启用'"
          >
            {{ '升版' }}
          </ElButton>
        </div>
        <div class="mr-10">
          <ElTag type="success">{{ currentRow?.status ?? '未创建' }}</ElTag>
          <ElTag type="success">{{ 'V' + (currentRow?.version ?? '1') }}</ElTag>
        </div>
      </div>
    </template>
  </ContentDetailWrap>

  <Dialog v-model="dialogVisible" title="选择零件">
    <Material ref="materialRef" />
    <template #footer>
      <ElButton type="primary" @click="onSelectPart">确定</ElButton>
      <ElButton @click="dialogVisible = false">{{ t('common.close') }}</ElButton>
    </template>
  </Dialog>
  <Dialog v-model="standVisible" title="选择标准">
    <Standard ref="standRef" />
    <template #footer>
      <ElButton type="primary" @click="onSelectStand">确定</ElButton>
      <ElButton @click="standVisible = false">{{ t('common.close') }}</ElButton>
    </template>
  </Dialog>
</template>

<style lang="less" scoped>
:deep(.el-collapse-item__header) {
  display: unset;
  font-size: 16px;
  font-weight: 600;
  background-color: #f2f2f2;
  margin-bottom: 20px;
}
:deep(.el-form-item) {
  margin-bottom: 18px;
}
:deep(.content_wrap .el-form-item) {
  margin-bottom: 0;
}
</style>
@/hooks/event/useEventBus
